package com.hzyl.famousreader.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.umeng.analytics.MobclickAgent;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.router.Router;
import com.hzyl.famousreader.databinding.*;
/**
 * 网络视图
 */
@Route(path = Router.ACTIVITY_WEB, name = "网络视图")
public class WebActivity extends AppCompatActivity {

  @Autowired
  String url;

  private ActivityWebBinding binding;

  protected AgentWeb mAgentWeb;
  private AlertDialog mAlertDialog;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ARouter.getInstance().inject(this);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_web);

    binding.toolbar.setTitleTextColor(Color.WHITE);
    binding.toolbar.setTitle("");

    this.setSupportActionBar(binding.toolbar);
    if (getSupportActionBar() != null) {
      // Enable the Up button
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        showDialog();
      }
    });

    long p = System.currentTimeMillis();

    mAgentWeb = AgentWeb.with(this)
      .setAgentWebParent(binding.webContainer, new LinearLayout.LayoutParams(-1, -1))
      .useDefaultIndicator()
      .setWebChromeClient(mWebChromeClient)
      .setWebViewClient(mWebViewClient)
      .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
      .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
      //.setWebLayout(new WebLayout(this))
      .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
      .interceptUnkownUrl() //拦截找不到相关页面的Scheme
      .createAgentWeb()
      .ready()
      .go(url);

    //mAgentWeb.getUrlLoader().loadUrl(getUrl());

    long n = System.currentTimeMillis();
    LogUtils.i("Info", "init used time:" + (n - p));


  }

  private WebViewClient mWebViewClient = new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
      return super.shouldOverrideUrlLoading(view, request);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
      //do you  work
      LogUtils.i("Info", "BaseWebActivity onPageStarted");
    }
  };
  private WebChromeClient mWebChromeClient = new WebChromeClient() {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
      //do you work
//            Log.i("Info","onProgress:"+newProgress);
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
      super.onReceivedTitle(view, title);
      if (binding.toolbarTitle != null) {
        binding.toolbarTitle.setText(title);
      }
    }
  };

  private void showDialog() {

    if (mAlertDialog == null) {
      mAlertDialog = new AlertDialog.Builder(this)
        .setMessage("您确定要关闭该页面吗?")
        .setNegativeButton("再逛逛", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            if (mAlertDialog != null) {
              mAlertDialog.dismiss();
            }
          }
        })//
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

            if (mAlertDialog != null) {
              mAlertDialog.dismiss();
            }
            WebActivity.this.finish();
          }
        }).create();
    }
    mAlertDialog.show();

  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (mAgentWeb.handleKeyEvent(keyCode, event)) {
      return true;
    }
    return super.onKeyDown(keyCode, event);
  }

  @Override
  protected void onPause() {
    mAgentWeb.getWebLifeCycle().onPause();
    super.onPause();
    MobclickAgent.onPageEnd("WebView");
    MobclickAgent.onPause(this);
  }

  @Override
  protected void onResume() {
    mAgentWeb.getWebLifeCycle().onResume();
    super.onResume();
    MobclickAgent.onPageStart("WebView");
    MobclickAgent.onResume(this);

  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    LogUtils.i("Info", "onResult:" + requestCode + " onResult:" + resultCode);
    super.onActivityResult(requestCode, resultCode, data);
  }


  @Override
  protected void onDestroy() {
    super.onDestroy();
    //mAgentWeb.destroy();
    mAgentWeb.getWebLifeCycle().onDestroy();
  }
}
